package cz.gelion.shylock.invoice.test

import javax.persistence.Persistence
import javax.persistence.EntityManager
import cz.gelion.shylock.invoice.entity.Manager
import cz.gelion.shylock.invoice.CurrentEnv
import java.util.List
import java.util.ArrayList
import cz.gelion.shylock.invoice.Log
import org.apache.log4j.Level
import org.apache.log4j.Logger
import org.apache.log4j.BasicConfigurator

object ConsoleInit extends Log {

  var man:Manager  = _
  
  def logLevel(l:Level) = Logger.getLogger("cz.gelion.shylock.invoice").setLevel(l)
  BasicConfigurator.configure()
  Logger.getLogger("org.hibernate").setLevel(Level.ERROR)
  log.info("Shylock invoice init...")
  
  def init(user:String) = {	
    man = em.find(classOf[Manager], user)
     CurrentEnv._manager.value = man
  }
  
  def manager = CurrentEnv._manager.value
  
  
  lazy val em = Persistence.createEntityManagerFactory("shylock").createEntityManager()
  
 
  
  
  def transaction[T](t:()=>T):Option[T] = {
   
    log.trace("")
    log.trace("transaction begins..")
    em.getTransaction().begin()
    
    try  {
    	val r = t() 
    
    	
    	em.getTransaction().commit()
    	log.trace("transaction commited")
    	Some(r)
  	} catch {
  	  case ex: Throwable => {
  	      log.error("Error in transaction", ex)
  	      log.trace("trasaction rollback")
  		  em.getTransaction().rollback()
  		  throw ex
  		None  
  	  }
  	} 
  }
  
  def query[T](q:String, c:Class[T], p:(String, Object)*):List[T] = {
    var qr = em.createQuery(q, c)
    for (a <- p) {
      qr.setParameter(a._1, a._2)
    }
    qr.getResultList()
  }
  
  
  
  def persist(o:Object) = {
    log.trace("persist(" + o + ")")
    transaction(() => {
      em.persist(o)  
    })
  }
  
  
}